using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;

public partial class ObjectFactory
{
    public FactoryType type;

	private Dictionary<string,ObjectPool> _pools = new Dictionary<string,ObjectPool>();

	public ObjectFactory(FactoryType type)
	{
		this.type = type;
    }

    GameObject LoadPrefabByPath(string Path)
    {
        GameObject go = (GameObject)(MonoBehaviour.Instantiate(Resources.Load(Path)));
        return go;
    }

    public GameObject Spawn(string slug)
    {
        ObjectPool pool = GetPool(slug);
        GameObject go = pool.Spawn();
        return go;
    }

    public void UnSpawn(GameObject go)
    {
        ObjectPool pool = ObjectPool.Obj2PoolDic[go];
        pool.UnSpawn(go);
        ObjectPool.Obj2PoolDic.Remove(go);
    }

    public ObjectPool GetPool(string slug)
    {
        if(_pools.ContainsKey(slug))
        {
            return _pools[slug];
        }
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("{0}{1}{2}{3}{4}", AssetPath, "/", type.ToString(), "/", slug);
        string s = sb.ToString();
        Debug.Log("s = "+ s);
        GameObject prefab = LoadPrefabByPath(s);
        Debug.Log("prefab = "+ prefab);
        ObjectPool pool = ObjectPool.Create(s,prefab,10);
        _pools[slug] = pool;
        pool.factory = this;
        return pool;
    }

    public void RemovePool(string slug)
    {
		ObjectPool pool = _pools[slug];
        if (pool == null) return;
        pool.Clear();
        _pools.Remove(slug);
    }

    public void Clear()
    {
		foreach (KeyValuePair<string, ObjectPool> pair in _pools)
		{
			pair.Value.Clear();
		}
		_pools.Clear();
            
    }	
}
